<template>
  <view style="padding: 10px;">
    <uni-forms ref="forms" :rules="rules" v-model="violationPatrolDetail">
      <uni-section title="违纪学生照片" type="line">
        <uni-forms-item :required="!isDetail">
          <view style="display: flex;">
            <view style="flex-direction: row;">
              <image-picker ref="imagePicker" :value.sync="violationPatrolDetail.images" :limit="1" @success="onSuccess" :readonly="isDetail" @change="onImageChange"/>
              <uni-view v-if="imageErrorShow">
                <uni-text class="rule-error-text"><span>请选择违纪学生照片</span></uni-text>
              </uni-view>
            </view>
            <view style="flex-direction: row;margin-top: 20rpx">
              <button type="primary" size="mini" @click="showAddDialog" v-if="!isDetail && this.isEmpty(violationPatrolDetail.studentName)">选择违纪学生</button>
              <view style="font-size: 20px; margin-bottom: 10px;">{{violationPatrolDetail.studentName?'学生姓名：'+violationPatrolDetail.studentName:''}}</view>
              <view style="font-size: 20px; ">{{violationPatrolDetail.className?'班级：'+violationPatrolDetail.className:''}}</view>
            </view>
            <view class="deleteStudent" @click="deleteStudent"  v-if="!isDetail && this.notEmpty(violationPatrolDetail.studentName)">x</view>
          </view>
        </uni-forms-item>
      </uni-section>
      <uni-section title="违纪类型" type="line" style="margin-top: 20rpx;" >
        <uni-forms-item name="violationType" :required="!isDetail">
          <dict-select :type="isDetail ? 'text' : 'radio'" ref="violationTypeNode" dict-type="violation_type" v-model="violationPatrolDetail.violationType"/>
        </uni-forms-item>
      </uni-section>
      <uni-section title="违纪学生人数" type="line" v-if="false">
        <uni-forms-item name="studentNum" :required="!isDetail">
          <text v-if="isDetail" style="margin-left: 20rpx">{{violationPatrolDetail.studentNum}}</text>
          <uni-number-box style="width: 500px" :min="1" :max="9" v-model="violationPatrolDetail.studentNum" v-else />
        </uni-forms-item>
      </uni-section>
      <uni-section title="违纪情况说明" type="line">
        <uni-forms-item>
          <text v-if="isDetail" style="margin-left: 20rpx">{{violationPatrolDetail.note}}</text>
          <uni-easyinput type="textarea" v-model="violationPatrolDetail.note" placeholder="请输入违纪情况" v-else />
        </uni-forms-item>
      </uni-section>
      <uni-section title="违纪处理结果" type="line">
        <uni-forms-item name="handleContent" :required="!isDetail">
          <text v-if="isDetail" style="margin-left: 20rpx">{{violationPatrolDetail.handleContent}}</text>
          <uni-easyinput type="textarea" v-model="violationPatrolDetail.handleContent" placeholder="请输入违纪处理情况" v-else />
        </uni-forms-item>
      </uni-section>
      <uni-section title="违纪时间" type="line" style="margin-top: 20rpx">
        <uni-forms-item name="violationTime" :required="!isDetail">
          <text v-if="isDetail" style="margin-left: 20rpx">{{violationPatrolDetail.violationTime}}</text>
          <uni-datetime-picker type="datetime" :clear-icon="false" :start="getTimestamp(-1,6,0)" :end="new Date().getTime()"
                               placeholder="选择请违纪时间" v-model="violationPatrolDetail.violationTime" v-else/>
        </uni-forms-item>
      </uni-section>
      <uni-section title="违纪已认领" type="line" style="margin-top: 20rpx;" v-if="notEmpty(violationReceiveInfos)">
        <uni-list>
          <uni-list-item
              thumb-size="lg"
              :title="item.studentName"
              :thumb="handleImageUrl(item.stuPhoto)"
              :note="item.className"
              :show-badge="true"
              :badge-text="getViolationText(item)"
              v-for="(item,index) in violationReceiveInfos"
              :key="index"/>
        </uni-list>
      </uni-section>
      <view style="display: flex;gap: 10rpx;margin-top: 20rpx;" v-if="!violationPatrolDetail || violationPatrolDetail.status!==4">
         <button type="primary" style="flex: 1" @click="openEdit" v-if="canEdit">编辑</button>
        <button type="primary" style="flex: 1" @click="save(false)" v-if="canSave">保存</button>
        <button type="primary" style="flex: 1" @click="save(true)" v-if="canSubmit">提交</button>
        <button type="warn" style="flex: 1" @click="del" v-if="canDel">删除</button>
        <button type="warn" style="flex: 1" @click="cancel" v-if="canCancel">取消</button>
      </view>
    </uni-forms>
	
	<uni-popup ref="popups" background-color="#fff">
	  <view class="popup-content">
	    <uni-data-select
	        v-model="classId"
	        :localdata="classOptions"
	        placeholder="请选择班级"
	        @change="changeClass">
	    </uni-data-select>
	    <scroll-view :scroll-y="true" style="max-height: 500rpx;margin-top: 10rpx;margin-bottom: 20rpx" @scrolltolower="loadMore">
	      <uni-list>
	        <uni-list-item
	            v-for="item in queryStudentInfos"
	            show-switch
	            :thumb="item.stuPhoto"
	            :title="item.studentName"
	            :note="item.className"
	            @switchChange="studentSwitchChange(item,$event)">
	        </uni-list-item>
	      </uni-list>
	    </scroll-view>
	    <button type="primary" @click="addNewViolationStudents">添加</button>
	  </view>
	</uni-popup>
  </view>
</template>

<script>
import violationPatrolApi from "../../api/modules/violationPatrol";
import {getTimestamp, toast} from "../../js/common";
import UniForms from "../../uni_modules/uni-forms/components/uni-forms/uni-forms.vue";
import UniFormsItem from "../../uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue";
import UniList from "../../uni_modules/uni-list/components/uni-list/uni-list.vue";
import UniListItem from "../../uni_modules/uni-list/components/uni-list-item/uni-list-item.vue";
import student from '@/api/modules/student'
import teacherClass from '@/api/modules/teachClass'
import DictSelect from "../../components/dict-select/index.vue";

export default {
  components: {DictSelect, UniListItem, UniList, UniFormsItem, UniForms},
  data() {
    return {
      id: null,
      topName: null,
      violationReceiveInfos: [],
      violationPatrolDetail: {},
      violationPatrolStatus: null,
	  needAddViolationStudentInfos: [],
	  queryStudentInfoPage : 1,
	  queryStudentInfoTotalPage : null,
	  queryStudentInfoPageSize: 10,
	  queryStudentInfos: [],
	  classOptions:[],
	  classId:null,
	  
      isSubmit: false,
      imageErrorShow: false,
      rules: {
        handleContent: {
          "rules": [
            { required: true, errorMessage: '请输入违纪处理内容', trigger: 'blur' }
          ]
        },
        violationType: {
          "rules": [
            {required: true, errorMessage: '请选择违纪类型', trigger: 'change'}
          ]
        },
        violationTime: {
          "rules": [
              {required: true, errorMessage: '请选择违纪时间', trigger: 'change'}
          ]
        },
        studentNum: {
          rules: [
            {required: true, errorMessage: '缺少违纪学生数量'}
          ]
        }
      },
      timeSlotOptions:[
        {
          text: "上午",
          value: 1
        },
        {
          text: "下午",
          value: 2
        },
        {
          text: "晚自习",
          value: 3
        }
      ]
    }
  },
  onLoad(option) {
    this.id = option.id;
    this.topName = this.id ? "违纪巡查详情" : '新增违纪巡查信息';
    this.getViolationPatrolDetail();
  },
  computed: {
    isAdd(){
      return this.topName === '新增违纪巡查信息';
    },
    isUpdate(){
      return this.topName === '修改违纪巡查信息';
    },
    isDetail(){
      return this.topName === '违纪巡查详情';
    },
    notReceive(){
      return this.violationPatrolStatus < 3;
    },
    canEdit() {
      // 详情且未接受时可编辑
      return this.notReceive && this.isDetail;
    },
    canSubmit() {
      // 未提交时可提交 因为去掉草稿状态所以需要不是详情状态
      return this.notReceive && !this.isDetail;
    },
    canSave() {
      // 去掉保存状态
      return false;
    },
    canDel() {
      // 没接受时且不是添加时可以删除
      return this.notReceive && !this.isAdd;
    },
    canCancel() {
      // 不是详情就可取消
      return !this.isDetail;
    }
  },
  methods: {
    deleteStudent(){
      this.violationPatrolDetail.studentName = null;
      this.violationPatrolDetail.className = null;
      this.violationPatrolDetail.classIds = null;
      this.violationPatrolDetail.studentIds = null;
      this.$forceUpdate();
    },
    getViolationText(classDv){
      // noinspection EqualityComparisonWithCoercionJS
      let timeSlotStr = this.timeSlotOptions.find(item=>item.value==classDv.timeSlot).text||"";
      // noinspection EqualityComparisonWithCoercionJS
      // let dvTypeStr = this.violationTypeOptions.find(item=>item.value==classDv.dvType).text||"";
      let dvTypeStr = this.$refs.violationTypeNode.getDictLabel(classDv.dvType)
      if(dvTypeStr && dvTypeStr.length>0){
        dvTypeStr+="违纪";
      }
      return timeSlotStr + dvTypeStr;
    },
    getTimestamp,
    onImageChange(imageFiles){
      this.imageErrorShow = imageFiles.length === 0;
      this.$set(this.violationPatrolDetail,"studentNum",imageFiles.length);
      console.log('onImageChange',this.violationPatrolDetail.studentNum);
    },
    onSuccess(){
      // 在编辑页面点击保存或提交
      let violationPatrolInfo = this.getSaveViolationPatrolInfo();
      if(violationPatrolInfo === null){
        this.toast('获取待操作信息失败',1000);
        return;
      }
      this.showLoadingBySubmit();
      violationPatrolApi.save(violationPatrolInfo).then(resp=>{
        this.hideLoading();
        if(resp.code === 200){
          this.toast('保存成功');
        }else {
          this.toast("保存失败");
        }
        this.goBack(500);
      }).catch(error=>{
        this.hideLoading();
        this.toast(this.getErrorResMsg(error));
      });
    },
    getSaveViolationPatrolInfo(){
      if(!this.violationPatrolDetail){
        return null;
      }
      return {
        id: this.violationPatrolDetail.id,
        images: this.violationPatrolDetail.images,
        studentNum: this.violationPatrolDetail.studentNum,
        note: this.violationPatrolDetail.note,
        handleContent: this.violationPatrolDetail.handleContent,
        violationTime: this.violationPatrolDetail.violationTime,
        submit: this.isSubmit,
        classIds: this.violationPatrolDetail.classIds ? this.violationPatrolDetail.classIds+'' : null,
        studentIds: this.violationPatrolDetail.studentIds ? this.violationPatrolDetail.studentIds+'' : null,
        violationType: this.violationPatrolDetail.violationType
      };
    },
    openEdit(){
      this.topName = '修改违纪巡查信息';
    },
    save(submit){
      // 详情页面提交
      if(submit && this.isDetail){
        // 在详情页面点击提交 不需要校验参数
        if(!this.violationPatrolDetail || !this.violationPatrolDetail.id){
          this.toast("获取违纪巡查编号失败");
          return;
        }
        // 开始提交
        violationPatrolApi.submit(this.violationPatrolDetail.id).then(resp=>{
          this.handleRes(resp).then(()=>{
            this.toast("提交成功");
            this.goBack(500)
          });
        });
        return;
      }

      // 编辑页面保存或提交
      let hasImageFile = this.$refs.imagePicker.hasImageFile();
      this.imageErrorShow = !hasImageFile;
      this.$refs.forms.validate(null,null).then(()=>{
        if(this.imageErrorShow){
          return;
        }
        this.isSubmit = submit;
        this.$refs.imagePicker.uploadImages();
      }).catch(err=>{
        console.log("保存提交时参数校验不通过",err);
      });
    },

    del(){
      violationPatrolApi.delete(this.id).then(resp=>{
        this.handleRes(resp).then(()=>{
          this.toast("删除成功");
          this.goBack(500);
        });
      });
    },
    cancel(){
      if(this.isUpdate){
        this.reload();
        return;
      }
      this.goBack();
    },
    getViolationReceiveInfos(){
      if(!this.id){
        return;
      }
      violationPatrolApi.getViolationPatrolReceiveInfos(this.id).then(res=>{
        this.handleRes(res,null,true).then(data=>{
          this.violationReceiveInfos = data;
        });
      }).catch(err=>{
        console.error("获取违纪认领信息失败",err);
        toast("获取违纪认领信息失败",1500,"error")
      });
    },
    getViolationPatrolDetail(){
      if(!this.id){
        this.violationPatrolDetail.violationTime = new Date().format("yyyy-MM-dd HH:mm:ss");
        return;
      }
      violationPatrolApi.getViolationPatrolDetailInfo(this.id).then(res=>{
        console.log("getViolationPatrolDetail",res);
        this.violationPatrolDetail = res.data;
        this.violationPatrolStatus = this.violationPatrolDetail.status;
        this.getViolationReceiveInfos();
      }).catch(err=>{
        console.error("获取违纪详情失败",err);
        uni.showToast({title: "获取违纪详情失败",icon: "error"});
        this.goBack(1000)
      });
    },
	getClassIdAndNames(){
	  teacherClass.getClassIdAndNames().then(res=>{
	    this.handleRes(res).then(data=>{
	      if(data){
	        data = data.map(item=>{
	          return {value: item.id,text:item.name};
	        })
	      }
	      this.classOptions = data;
	    })
	  });
	},
	getStudentList(){
	  let paras = {page: this.queryStudentInfoPage,pageSize: this.queryStudentInfoPageSize,classId:this.classId};
	  student.getFilterStudentPage(paras).then(res=>{
	    this.handleRes(res).then(data=>{
	      let list = this.trimAddStudentInfos(data.list);
	      this.queryStudentInfos=[...this.queryStudentInfos,...list]
	      this.queryStudentInfoTotalPage=data.totalPage;
	    });
	  })
	},
	trimAddStudentInfos(studentInfos){
	  if(this.isEmpty(studentInfos)){
	    return studentInfos;
	  }
	  if(this.notEmpty(this.needAddViolationStudentInfos)){
	    let ids = this.needAddViolationStudentInfos.map(item=>item.id);
	    let idSet = new Set(ids);
	    studentInfos = studentInfos.filter(info=>!idSet.has(info.id));
	  }
	  if(this.notEmpty(this.violationReceiveInfos)){
	    let ids = this.violationReceiveInfos.map(item=>item.studentId);
	    let idSet = new Set(ids);
	    studentInfos = studentInfos.filter(info=>!idSet.has(info.id));
	  }
	  return studentInfos;
	},
	changeClass(){
	  this.resetStudentQueryContext();
	  this.getStudentList();
	},
	resetStudentQueryContext(resetCLassId=false){
	  this.queryStudentInfos = [];
	  this.queryStudentInfoPage = 1;
	  this.queryStudentInfoTotalPage = null;
	  if(resetCLassId){
	    this.classId = null;
	  }
	},
	loadMore(){
	  if(this.queryStudentInfoTotalPage && this.queryStudentInfoPage >= this.queryStudentInfoTotalPage){
	    console.log("所有数据已加载完毕,无需在加载");
	    return;
	  }
	  this.queryStudentInfoPage++;
	  this.getStudentList();
	},
	studentSwitchChange(student,event){
	  student.checked = event.value;
	},
	addNewViolationStudents(){
	  let studentInfos = this.queryStudentInfos.filter(item=>item.checked);
	  if(studentInfos.length > 1){
	    this.toast("最多添加"+1+"个违纪学生");
	    return;
	  }
	  this.violationPatrolDetail.studentName = studentInfos[0].studentName
	  this.violationPatrolDetail.className = studentInfos[0].className
	  this.violationPatrolDetail.classIds = studentInfos[0].classId
	  this.violationPatrolDetail.studentIds = studentInfos[0].id
	  this.$forceUpdate()
	  this.$refs.popups.close();
	},
	showAddDialog(){
	  if(this.isEmpty(this.classOptions)){
	    this.getClassIdAndNames();
	  }
	  if(this.isEmpty(this.queryStudentInfos)){
	    this.getStudentList();
	  }
	  this.$refs.popups.open("center");
	},
  }
}
</script>

<style>
	.popup-content {
	  width: 500rpx; /* 或固定宽度，如 300px */
	  margin: 0 auto; /* 水平居中 */
	  padding: 20px;
	}
  .rule-error-text {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    transition: transform 0.3s;
    transform: translateY(-100%);
  }
  .deleteStudent{
    // 加定位 父级要加相对定位
    position: absolute;
    // 位置右上角
    right: 0;
    top: 0;
    width: 50rpx;
    height: 50rpx;
    background: rgba(0,0,0,0.7);
    color: #fff;
    border-radius: 0 0 0 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    padding-bottom: 16rpx;
    padding-left: 8rpx;
    margin-top: 20rpx;
  }
</style>
